# apps/audit/api.py
from rest_framework import viewsets, filters
from rest_framework.permissions import IsAuthenticated, DjangoModelPermissions
from django_filters import rest_framework as django_filters
from django_filters import FilterSet, CharFilter, DateTimeFilter, ChoiceFilter
from .models import AuditLog
from .permissions import CustomDjangoModelPermissions
from .serializers import AuditLogSerializer

class AuditLogFilter(FilterSet):
    action = ChoiceFilter(choices=AuditLog.ACTION_CHOICES)
    model_name = CharFilter(lookup_expr='icontains')
    username = CharFilter(field_name='username', lookup_expr='icontains')
    object_repr = CharFilter(lookup_expr='icontains')
    ip_address = CharFilter()
    start_date = DateTimeFilter(field_name='timestamp', lookup_expr='gte')
    end_date = DateTimeFilter(field_name='timestamp', lookup_expr='lte')

    class Meta:
        model = AuditLog
        fields = ['action', 'model_name', 'username', 'ip_address', 'start_date', 'end_date']


class AuditLogViewSet(viewsets.ReadOnlyModelViewSet):
    """
    审计日志 API
    支持按操作、模型、用户、时间范围过滤
    """
    serializer_class = AuditLogSerializer
    permission_classes = [IsAuthenticated,CustomDjangoModelPermissions]
    filter_backends = [django_filters.DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_class = AuditLogFilter
    search_fields = ['username', 'object_repr', 'changes']
    ordering = ['-timestamp']
    ordering_fields = ['timestamp', 'username', 'action']

    def get_queryset(self):
        # 多租户隔离
        tenant = getattr(self.request.user, 'tenant', None)
        if tenant:
            return AuditLog.objects.filter(tenant=tenant)
        return AuditLog.objects.none()  # 无租户则无权限